package com.zhongxi.guoyuan.view.user;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.user.UploadResult;
import com.zhongxi.guoyuan.entity.user.UseInfo;
import com.zhongxi.guoyuan.entity.user.UserData;
import com.zhongxi.guoyuan.entity.user.UserResult;
import com.zhongxi.guoyuan.entity.user.WeiXinLogin;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.utils.FileTool;
import com.zhongxi.guoyuan.utils.UiUtils;
import com.zhongxi.guoyuan.view.MainHomeActivity;
import com.zhongxi.guoyuan.view.rewardCoin.RewardAddressListActivity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

public class UserInfoSettingActivity extends BaseActivity implements View.OnClickListener {

    private ImageView ivHead;
    private TextView tvStoreName;
    private RelativeLayout relaHead;
    private RelativeLayout relaName;
    private RelativeLayout relaAddress;
    private Bitmap bitmap;
    private String type;
    private EditText etSetName;
    private RelativeLayout relaModifyPassword;
    private RelativeLayout bindPhoneorWX;
    private ImageView ivPhoneOrWX;
    private TextView tvPhoneorWX;

    private MediaScannerConnection mMediaonnection;
    private File origPicFile;
    private File absolutePicFile;
    private String timeStamp;
    private AlertDialog dialog;
    private DialogInterface.OnKeyListener onKeyListener = new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialogInterface, int keyCode, KeyEvent keyEvent) {
            if (keyCode == KeyEvent.KEYCODE_BACK && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                return true;
            }
            return false;
        }
    };
    private String mOpenid;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_user_info_setting);
        initTitle();
        tvTitle.setText("个人设置");
        ivHead = (ImageView) findViewById(R.id.ivHead);
        tvStoreName = (TextView) findViewById(R.id.tvStoreName);
        relaHead = (RelativeLayout) findViewById(R.id.relaHead);
        relaName = (RelativeLayout) findViewById(R.id.relaName);
        relaAddress = (RelativeLayout) findViewById(R.id.relaModifyAddress);
        relaModifyPassword = (RelativeLayout) findViewById(R.id.relaModifyPassword);
        bindPhoneorWX = (RelativeLayout) findViewById(R.id.relaModifyPhoneorWx);
        ivPhoneOrWX = (ImageView) findViewById(R.id.iv_phorwx);
        tvPhoneorWX = (TextView) findViewById(R.id.tv_modify_content);

    }


    @Override
    protected void initData() {
        super.initData();
        if (null != MyApplication.getInstance().getUserName() && !"".equals(MyApplication.getInstance().getUserName())) {
            tvStoreName.setText(MyApplication.getInstance().getUserName());
        }
        Glide.with(this).load(Url.BASE_URL + MyApplication.getInstance().getAvatar())
                .placeholder(R.mipmap.iv_eg)
//                .transform(new GlideRoundTransform(this, 20))
                .into(ivHead);

        if (!TextUtils.isEmpty(MyApplication.getInstance().getPhone()) && !TextUtils.isEmpty(MyApplication.getInstance().getAppOpenid())) {
            bindPhoneorWX.setVisibility(View.GONE);
        } else if (TextUtils.isEmpty(MyApplication.getInstance().getPhone())) {
            tvPhoneorWX.setText(getResources().getString(R.string.bindphone));
            ivPhoneOrWX.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.iv_modify_phone));

        } else if (TextUtils.isEmpty(MyApplication.getInstance().getAppOpenid())) {
            tvPhoneorWX.setText(getResources().getString(R.string.bindwx));
            ivPhoneOrWX.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.iv_modify_wx));

        }
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        relaHead.setOnClickListener(this);
        relaName.setOnClickListener(this);
        relaAddress.setOnClickListener(this);
        relaModifyPassword.setOnClickListener(this);
        bindPhoneorWX.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.relaHead:
                popHeadDialog();
                break;
            case R.id.relaName:
                popNameDialog();
                break;
            case R.id.relaModifyPassword:
                startAct(ModifyPasswordActivity.class);
                break;
            case R.id.relaModifyAddress:
                startAct(RewardAddressListActivity.class);
                break;
            case R.id.relaModifyPhoneorWx:
                if (tvPhoneorWX.getText().toString().trim().equals(getResources().getString(R.string.bindphone))) {
                    startAct(RegisterActivity.class);
                } else if (tvPhoneorWX.getText().toString().trim().equals(getResources().getString(R.string.bindwx))) {//绑定微信
                    type = "weixin";
                    getServer(Url.WXAUTH, null, "", false, null, "get");
                }
                break;
        }
    }

    /**
     * 弹出头像
     */
    private void popHeadDialog() {
        initFile();
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_head_setting, null);
        dialog = new AlertDialog.Builder(context).create();
        dialog.setView(layout);
        dialog.setOnKeyListener(onKeyListener);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        ImageView ivCancel = (ImageView) layout.findViewById(R.id.ivCancel);
        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        TextView tvSelect = (TextView) layout.findViewById(R.id.tvSelect);
        TextView tvTakePhone = (TextView) layout.findViewById(R.id.tvTakePhone);
        tvSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {   //相册
                getPhoto();
                dialog.dismiss();
            }
        });
        tvTakePhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AndPermission.with(context)
                        .requestCode(100)
                        .permission(Permission.CAMERA)
                        .callback(new PermissionListener() {
                            @Override
                            public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                                takePhoto();
                            }

                            @Override
                            public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                                showShortToast("设置头像失败");
                            }
                        })
                        .start();
                dialog.dismiss();
            }
        });
    }

    private void initFile() {
        // 输出裁剪的临时文件的时间
        timeStamp = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA).format(new Date());
        // 照片命名
        String origFileName = "pic_origin_" + timeStamp + ".jpg";
        String cropFileName = "pic_after_crop_" + timeStamp + ".jpg";

        // 裁剪头像的绝对路径
        String absolutePicPath = FileTool.getRootFilePath() + cropFileName;
        absolutePicFile = new File(absolutePicPath);
        origPicFile = new File(FileTool.getRootFilePath(), origFileName);
    }

    private void getPhoto() {  //相册
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        /* 取得相片后返回本画面 */
        startActivityForResult(intent, 1);
    }

    private void takePhoto() {   //相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri picUri = null;
        if (Build.VERSION.SDK_INT < 24) {
            picUri = Uri.fromFile(origPicFile);
        } else {
            picUri = FileProvider.getUriForFile(context, context.getResources().getString(R.string.authorities), origPicFile);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
        startActivityForResult(intent, 0);// 采用ForResult打开
    }


    /**
     * 弹出设置名称dialog
     */
    private void popNameDialog() {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_name_setting, null);
        final AlertDialog dialog = new AlertDialog.Builder(context).create();
        dialog.setView(layout);

        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.show();

        TextView tvComplete = (TextView) layout.findViewById(R.id.tvComplete);
        ImageView ivCancel = (ImageView) layout.findViewById(R.id.ivCancel);
        TextView tv_oldName = (TextView) layout.findViewById(R.id.tv_oldName);
        tv_oldName.setText(MyApplication.getInstance().getUserName());
        etSetName = (EditText) layout.findViewById(R.id.etSetName);
        //取消
        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        //设置名称
        tvComplete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(etSetName.getText().toString().trim())) {
                    showShortToast("名称不能为空!");
                } else {
                    CommonTool.hideSoft(etSetName, UiUtils.getContext());
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("username", etSetName.getText().toString().trim());
                    type = "shopname";
                    getServer(Url.SET_USERNAME, map, "", false, null, "post");
                    dialog.dismiss();
                }
            }
        });
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try {
            if ("shopname".equals(type)) {
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                MyApplication.getInstance().sharedPrefrences.edit().putString("username", etSetName.getText().toString().trim()).commit();
                tvStoreName.setText(etSetName.getText().toString().trim());
                showShortToast("设置用户名成功！");
            } else if ("uploadImg".equals(type)) {
                UploadResult result = gson.fromJson(response, UploadResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                if (null != result.getAvatar() && !"".equals(result.getAvatar())) {
                    MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", result.getAvatar()).commit();
                    showShortToast("设置用户头像成功！");
                }
            } else if (type.equals("weixin")) {
                WeiXinLogin mWeiXinLogin = gson.fromJson(response, WeiXinLogin.class);
                MyApplication.getInstance().setSpValue(mWeiXinLogin.safeobj);
                String mDescsc = MyApplication.getInstance().parseSecutiryKey(mWeiXinLogin.data);
                if (!TextUtils.isEmpty(mWeiXinLogin.authcode)) {
                    if (CommonTool.checkWxExist(this)) {
                        wxLogin(mWeiXinLogin.authcode);
                    } else {
                        showShortToast(getString(R.string.noInstall_wx));
                    }
                }
            } else if ("login".equals(type)) {
                UserResult result = gson.fromJson(response, UserResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                if (null != result.getData() && !"".equals(result.getData())) {
                    UserData data = result.getData();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("phone", result.getData().getMphone()).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("userid", result.getData().getId()).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("username", result.getData().getUsername()).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("shopname", result.getData().getShopname()).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", result.getData().getAvatar()).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("time", result.getData().getCtime()).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("appopenid", result.getData().getAppopenid()).commit();
                    if (null != data.getIsshareholders() && !"".equals(data.getIsshareholders())) {  //股东
                        MyApplication.getInstance().sharedPrefrences.edit().putBoolean("shareHolder", "1".equals(data.getIsshareholders())).commit();
                    }
                    if (null != data.getIsshareholders() && !"".equals(data.getIsshareholders())) {  // 消费收益人
                        MyApplication.getInstance().sharedPrefrences.edit().putBoolean("beneficiary", "1".equals(data.getIsbeneficiary())).commit();
                    }
                    if (null != data.getIsshareholders() && !"".equals(data.getIsshareholders())) {  //商家
                        MyApplication.getInstance().sharedPrefrences.edit().putBoolean("merchants", "1".equals(data.getIsmerchants())).commit();
                    }

                    if (null != String.valueOf(data.getIspartner())) {
                        MyApplication.getInstance().sharedPrefrences.edit().putBoolean("partener", 1 == data.getIspartner()).commit();
                    }
                    JPushInterface.setAlias(context, MyApplication.getInstance().getUserId(), new TagAliasCallback() {
                        @Override
                        public void gotResult(int i, String s, Set<String> set) {
                            if (i == 0) {
                                Log.d("LoginActivity", s);
                            }
                        }
                    });
                }
                if (null != result.getExtend() && !"".equals(result.getExtend())) {
                    UseInfo extend = result.getExtend();
                    if (null != extend.getInnercurrency() && !"".equals(extend.getInnercurrency())) {
                        MyApplication.getInstance().sharedPrefrences.edit().putString("inner", extend.getInnercurrency()).commit();
                    }

                    if (null != extend.getSharesgains() && !"".equals(extend.getSharesgains())) {
                        MyApplication.getInstance().sharedPrefrences.edit().putString("share", DataUtil.formatData(extend.getSharesgains())).commit();  //股份收益
                    }
                }

                startAct(MainHomeActivity.class);
                finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void wxLogin(final String authcode) {
        UMShareAPI.get(this).getPlatformInfo(this, SHARE_MEDIA.WEIXIN, new UMAuthListener() {

            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                //  o8sNlwgnjClXeZZzZ4xwdV041PuQ
                mOpenid = map.get("openid");
                String WxName = map.get("name");
                if (!TextUtils.isEmpty(mOpenid)) {
                    type = "login";
                    Map<String, String> maps = new HashMap<>();
                    maps.put("authcode", authcode);  //  ZDdhNGJlM2RlNzUyMWQ0Y4zuQZfqJWsHOlespsLqHkgL4CLWCUSLSkUEw7uPg!Dn
                    maps.put("openid", mOpenid);
                    getServer(Url.WXCHECK, maps, "", false, null, "post");
                } else {
                    showShortToast("授权登录失败");
                }
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                showShortToast("授权登录失败");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                showShortToast("授权登录取消");
            }
        });
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try {
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
            if (result.getCode() == 100) {
                showShortToast("参数错误");
            } else if (result.getCode() == 1001) {
                showShortToast("用户未登录");
            } else if (result.getCode() == 1666) {
                showShortToast("服务不可用，服务器异常");
            } else if (result.getCode() == 4005) {
                showShortToast("头像上传失败");
            } else if (result.getCode() == 4006) {
                showShortToast("上传文件大小超限");
            } else if (result.getCode() == 4007) {
                showShortToast("不是有效的图片文件");
            } else if (result.getCode() == 1003) {
                showShortToast("用户已登录");
            } else if (result.getCode() == 1004) {   // 微信新用户未注册
                showShortToast("用户未注册，请先注册");
                MyApplication.getInstance().sharedPrefrences.edit().putString("appopenid", mOpenid).commit();
                Intent mIntent = new Intent(this, RegisterActivity.class);
                startActivity(mIntent);
                finish();
            } else if (result.getCode() == 1005) {   // 微信登录的老用户
                showShortToast("老用户,还没有注册手机号呦!");
                Intent mIntent = new Intent(this, RegisterActivity.class);
                if (!TextUtils.isEmpty(mOpenid)) {
                    MyApplication.getInstance().sharedPrefrences.edit().putString("appopenid", mOpenid).commit();
                }
                mIntent.putExtra("useid", result.getId());
                startActivity(mIntent);
                finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            switch (requestCode) {
                case 0:            //相机
                    if (resultCode == RESULT_OK) {
                        final String img_path = FileTool.getRootFilePath() + "pic_origin_" + timeStamp + ".jpg";   //    /storage/emulated/0/meirongyuan/head.jpg
//                        MediaStore.Images.Media.insertImage(getContentResolver(), img_path, "pic_origin_" + timeStamp, null);   //将拍的img_path的照片保存系统相册中
                        mMediaonnection = new MediaScannerConnection(context, new MediaScannerConnection.MediaScannerConnectionClient() {   //刷新系统相册,显示刚拍的图片
                            @Override
                            public void onMediaScannerConnected() {
                                mMediaonnection.scanFile(img_path, "pic_origin_" + timeStamp);
                            }

                            @Override
                            public void onScanCompleted(String path, Uri uri) {
                                mMediaonnection.disconnect();
                            }
                        });
                        mMediaonnection.connect();
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            Uri picUri = FileProvider.getUriForFile(context, context.getResources().getString(R.string.authorities), origPicFile);
                            startPhotoZoom(picUri);
                        } else {
                            startPhotoZoom(Uri.fromFile(origPicFile));
                        }
                    }
                    break;
                case 1:                  //相册
                    if (resultCode == RESULT_OK) {
                        Uri sourceUri = data.getData();
                        startPhotoZoom(sourceUri);
                    }
                    break;
                case 2:
                    if (data != null) {
                        Bundle extras = data.getExtras();
                        if (extras != null) {
                            bitmap = extras.getParcelable("data");
                            try {
                                FileOutputStream fout = new FileOutputStream(absolutePicFile);
                                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fout);  //  0-100 100为不压缩
                                fout.flush();
                                fout.close();
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }
                            ivHead.setImageBitmap(bitmap);
                            uploadHead(absolutePicFile);
                        }
                    }
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 用户上传头像
     *
     * @param absolutePath
     */
    private void uploadHead(File absolutePath) {
        try {
            type = "uploadImg";
            uploadServer(Url.UPLOAD_AVATAR, false, null, absolutePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void startPhotoZoom(Uri imageUri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.setDataAndType(imageUri, "image/*");    // 源文件地址
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);    // aspectX aspectY是宽高比例
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 150);  // outputX outputY 是裁剪图片的宽高
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);   // 是否返回uri
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        startActivityForResult(intent, 2);
    }
}
